package ltd.followkba;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.kcbsdk.ASendInfo;
import com.kcbsdk.EventHandler;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSEND;
import ltd.advskin.MSKIN;
import ltd.advskin.VARIA;
import ltd.advskin.base.BaseInput;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.base.MPAGE;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.advskin.view.KcSendingView;
import ltd.followkba.page.AddTaskPage;
import ltd.followkba.page.TipsPage;
import ltd.followkba.task.App32;
import ltd.followkba.task.BDbsAccount;
import ltd.followkba.page.EditTaskPage;
import ltd.followkba.task.BWriteLock;
import ltd.followkba.task.TaskEach;
import ltd.followkba.task.WorksQueue;
import ltd.followkba.task.LogTyp;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class MainPage extends BaseList {
    private boolean isActive;
    private int gSuccessQty;
    private int gSuccessAll;
    private View kbtMain;
    private KcSendingView ksvMain;
    private int gSending;


    private int[] tabAppImage = new int[]{
            R.drawable.cnkc, R.drawable.cnkc, R.drawable.cnkc, R.drawable.cnkc,
            R.drawable.cnkc, R.drawable.cnkc, R.drawable.changba, R.drawable.changba,
            R.drawable.qmks, R.drawable.kuwokg, R.drawable.aichang, R.drawable.haochang,
            R.drawable.haochang, R.drawable.haochang,

    };

    public void MLOG(String text) {
        MSTRING(MAPI.GET_LOG_NAME(this) + text);
    }

    @Override
    public void onInitView() {
        setLayout(R.layout.page_run_task);
        MAPP.mWorksType = MAPP.makeArrayType(MSKIN.getStringArray(R.array.task_works_type));
        MAPP.mWorksName = MSKIN.getStringArray(R.array.task_full_name);
        gTabSelect = (byte) MSKIN.getMemoryInt(W.IncFans_gTabSelect, false);
        if (gTabSelect >= MAPP.mWorksType.length){
            gTabSelect = 0;
        }

        mKcHeaderView = findViewById(R.id.khvMain);
        //表数据提示减少最后一个字确定左边大还是右边大
        mKcHeaderView.setTitle("开始", new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch(type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        break;
                    case KcHeaderView.TYPE_CLICK_RIGHR:
                        MAPP.startSettingPage();
                        break;
                }
            }
        });
        mKcHeaderView.setLeft(-1, " ");
        mKcHeaderView.setRight(-1, "设置");
        kbtMain = findViewById(R.id.kbtMain);
        ksvMain = findViewById(R.id.ksvMain);
        initTabList();

        if (MAPP.mLockTask == null) {
            MAPP.mLockTask = new Object();
            MAPP.gSuccessQty = new int[MAPP.mWorksType.length];
            MAPP.mBLock32 = new BWriteLock();
            MAPP.mBLock33 = new BWriteLock();

            makeBDbsAccount(true);
            WorksQueue.setStart();              // 全局只开一个，用于查找所有类型的榜单及用户数据

            if (!MSKIN.getMemoryBoolean(W.PowerOnTips, false)) {
                MSKIN.setMemoryBoolean(W.PowerOnTips, true, false);
                MAPP.startTipsPage();
            }
            MAPP.startTaskService(true);
            MAPP.ignoreSSLHandshake();
        }
        ksvMain.setReadMode(true);
    }

    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (mMyWorks.isEventDataRefresh()){
//                    MLOG(String.format("isEventDataRefresh A %s %s %s",  MRAM.gServerNumber, MSKIN.getCurrentUserID(), mMyUtils.checkIsLogin()));
                    showInfo();
                }
            }
        });
        MSEND.setListener(ksvMain, new MSEND.Listener() {
            @Override
            public void onMessage(ASendInfo aSendInfo) {

            }
        });
//        MLOG(String.format("AddTaskPageC %s", mMyWorks.mEventHandler));
        showInfo();

    }

    @Override
    public void onPageUpdate(BasePage basePage){    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        Object object = getPageResult(basePage);
//        MLOG("AddTaskPageA");
        if (object != null){
//            MLOG("AddTaskPageB");
            makeBDbsAccount(false);
        }
        if (basePage instanceof TipsPage){
            if (MAPP.gManageLogin == 0 && MAPI.isEmpty(MSKIN.getMemoryString(W.ManageLoginFlag, false))) {
                MAPP.gManageLogin = 2;
                MAPP.startLoginManagePage();
            }
        }
        onInitData();
    }
    @Override
    public void onFinish(){
    }
    public void onTime(boolean isThread){                                                           // 被TaskService调用
        if (isThread){                                                                              // 后台线程回调返回，只能用于加载数据，不能接触View
            if (MAPP.mTaskEach != null) {
                synchronized (MAPP.mLockTask) {
                    int successQty = 0;
                    int successTotal = 0;
                    for (int index = 1; index < MAPP.mTaskEach[gTabSelect].length; index++) {      // 先将所有运行的停止掉
                        successQty += MAPP.mTaskEach[gTabSelect][index].SuccessQty;
                        successTotal += MAPP.mTaskEach[gTabSelect][index].mBDbsAccount.SuccessQty;
                    }
                    gSuccessQty = successQty;
                    gSuccessAll = successTotal;
                }
            }
            if (MAPP.gStartDateTime == 0) {
                MAPP.gStartDateTime = mMyUtils.getCurrentDate();
            }
            return;
        }
        if (mMyUtils.getServerNumber() > 0) {
            if (MAPP.gManageLogin > 0) {
                if (MAPP.gManageLogin == 1) {
                    MAPP.gManageLogin = 2;
                    MAPP.startLoginManagePage();
                }
            }
        }
        setListView(gTabSelect);
        isActive = !isActive;
        showInfo();
        if (MRAM.mTaskSysUpdate != null && MRAM.mTaskSysUpdate.checkBusy()) {
            int percent = MRAM.mTaskSysUpdate.getPercent();
            MLOG(String.format("TaskSysUpdate:%d%% file:%s", percent - 2, MRAM.mTaskSysUpdate.getFileName()));
            if (percent >= 102){
                MRAM.mTaskSysUpdate = null;
            }
        }
        if (gSending > 0) {
            ksvMain.setSending(MSEND.MODE_QTY, 1, 1000 * gSending++, null);
        }
    }
    private void showInfo(){
        int tabSel = getTabList();
        if (tabSel > 0) {
            tabSel -= 1;
            if (MAPP.mTaskEach != null) {
                synchronized (MAPP.mLockTask) {
                    setListView(tabSel, MAPP.mTaskEach[tabSel]);
                }
            }
        }
        mKcHeaderView.setTitle(String.format("%s主页%s%s", MAPP.mWorksName[MAPP.mWorksType[gTabSelect]], isActive?"@":"#", mMyUtils.getServerNumber()));
        if (MAPP.gStartDateTime != 0) {
            MSKIN.setText(String.format("%s(%s)", mMyUtils.getSmartDate(MAPP.gStartDateTime), MAPP.gSuccesslAll), kbtMain);
//            MLOG(String.format("AccountA Al %s %s", MAPP.gStartDateTime, mMyUtils.getSmartDate(MAPP.gStartDateTime)));
        }
    }
    private void makeBDbsAccount(boolean powerOn){
        setSending(true);
        new TaskFree(powerOn, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
//                    MSLEEP(9100);
                    boolean powerOn = (object instanceof Boolean) ? (Boolean)object : false;
//                    if (powerOn) {
                    MDBS.setRootPath();
                    String accountName = MSKIN.getMemoryString(W.ManageAccountName, false);
                    MDBS.checkPathExist(MDBS.getDbsPath((byte)32));
                    MAPP.mManageAccount = MDBS.getBDbsAccount((byte)32, accountName);
                    MLOG(String.format("AccountA getAccountPath %s %s", MAPP.mManageAccount, MDBS.getAccountPath((byte)32, accountName)));
                    for (int tabTyp = 0; tabTyp < MAPP.mWorksType.length; tabTyp++) {
                        byte appType = MAPP.mWorksType[tabTyp];
                        if (appType < 32)
                            appType = 32;                         // 相同类型的账号，统一放在一个地方
                        if (appType == 49) appType = 33;
                        MDBS.checkPathExist(MDBS.getUserPath(appType));
                    }
                    for (int tabTyp = 0; tabTyp < MAPP.mWorksType.length; tabTyp++) {
//                MDBS.checkPathExist(MDBS.getAccountPath(mWorksType[tabTyp]));
                        byte appType = MAPP.mWorksType[tabTyp];
                        MDBS.checkPathExist(MDBS.getWorksPath(appType));
                        MDBS.checkPathExist(MDBS.getCommentPath(appType));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.NORMAL_COMMENT));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.NEW_COMMENT));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.OLD_COMMENT));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.CARE_TEXT));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.GIFT_TEXT));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.ADVERT_TEXT));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.LOG_LIKE));
                        MDBS.checkPathExist(MDBS.getLogPath(appType, LogTyp.LOG_FILE));
                    }
                    while (!MAPP.threadStop) {               // 还没有下载成功mKcAGiftBean 会提示 后台忙，请稍候再试
                        if (MAPP.mKcAGiftBean != null) {
                            break;
                        }
                        MSLEEP(1000);
                        if (MAPP.gErrorManage != null) {
                            MRAM.mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ksvMain.setSending(MSEND.MODE_STRING, 1, 0, MAPP.gErrorManage);
                                }
                            });
                        }
                    }


                    App32.setPause(true);
//                    MAPP.pauseTaskEach = true;
                    if (MAPP.mTaskEach != null) {
                        MLOG("AccountA makeBDbsAccountA 重新分配账号");
                        synchronized (MAPP.mLockTask) {
//                            MLOG("AccountA makeBDbsAccountA B "+MAPP.mTaskEach.length);
                            for (int tabTyp = 0; tabTyp < MAPP.mTaskEach.length; tabTyp++) {      // 先将所有运行的停止掉
//                                MLOG("AccountA makeBDbsAccountA C "+MAPP.mTaskEach[tabTyp].length);
                                if (MAPP.mTaskEach[tabTyp].length > 1) {                        // 注意第0个不是正常的任务
                                    for (int index = 1; index < MAPP.mTaskEach[tabTyp].length; index++) {      // 先将所有运行的停止掉
                                        MAPP.MTOAST(String.format("正在停止%s任务%s", MAPP.mWorksName[tabTyp], MAPP.mTaskEach[tabTyp][index].mBDbsAccount.AccountName));
//                                        MLOG(String.format("AccountA makeBDbsAccountA 停止原来的运行 %s %s", tabTyp, index));
                                        MAPP.mTaskEach[tabTyp][index].setStop();
                                    }
                                }
                            }
                        }
                    }
                    MAPP.mTaskEach = new TaskEach[MAPP.mWorksType.length][];
                    synchronized (MAPP.mLockTask) {                                                 // 线程同步锁
                        for (int tabTyp = 0; tabTyp < MAPP.mWorksType.length; tabTyp++) {
                            List<BDbsAccount> lists = MDBS.getBDbsAccount(MAPP.mWorksType[tabTyp]);
                            int length = (lists != null) ? lists.size() : 0;
                        MLOG(String.format("AccountA makeBDbsAccountA C %s %s %s", tabTyp, MAPP.mWorksType[tabTyp], length));
                            MAPP.mTaskEach[tabTyp] = new TaskEach[length + 1];
                            MAPP.mTaskEach[tabTyp][0] = new TaskEach();                             // 在列表前面加一个空的任务用于总状态显示及增加任务
                            if (length > 0) {
                                Collections.sort(lists, new Comparator<BDbsAccount>() {
                                    public int compare(BDbsAccount info1, BDbsAccount info2) {
                                        return (info1.SetConfig[1] - info2.SetConfig[1]);           // 降序
                                    }
                                });
                                for (int index = 0; index < length; index++) {                      // 打开各自
                                    MAPP.mTaskEach[tabTyp][index + 1] = new TaskEach(lists.get(index));
                                }
                            }
                            if (MAPP.mWorksType[tabTyp] == 33) {
                                WorksQueue.setApp33(MAPP.mTaskEach[tabTyp]);
                            }
                        }
                    }
                    MLOG(String.format("AccountA Ak %s %s %s", MAPP.mTaskEach[0].length, MAPP.mTaskEach[1].length, MAPP.mTaskEach[2].length));
                    App32.setPause(false);
                    return;
                }

                    setSending(false);

                showInfo();
            }
        });
    }

    private void setSending(boolean enable){
        if (enable){
            gSending = 1;
        }else {
            gSending = 0;
            ksvMain.setSending(MSEND.MODE_DONE, 0, 0, null);
        }
    }


    private void startPage(View view){
        if (MAPP.mManageAccount != null) {
            TaskEach taskEach = (TaskEach) view.getTag();
            if (taskEach != null && taskEach.mBDbsAccount != null) {
                EditTaskPage editTaskPage = new EditTaskPage();
                editTaskPage.mBaseInput = new BaseInput(taskEach.mBDbsAccount);
                MPAGE.startBasePage(editTaskPage);
            } else {
                AddTaskPage addTaskPage = new AddTaskPage();
//                String appName = MSKIN.getStringArray(R.array.task_full_name)[gTabSelect];
                byte worksType = MAPP.mWorksType[gTabSelect];
                addTaskPage.mBaseInput = new BaseInput(MAPP.mWorksName[worksType], worksType);
//                addTaskPage.mBaseInput = new BaseInput(appName, worksType);
                MPAGE.startBasePage(addTaskPage);
            }
        }else if (MAPP.mKcAGiftBean == null){               // 还没有下载成功mKcAGiftBean
            MTOAST("后台忙，请稍候再试", 3000);
        }else {                                             //  MAPP.mManageAccount == null
            MTOAST("请先操作号登录", 3000);
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private static final int[] item_inc_fans = new int[]{
            R.layout.item_tab_task, 8,
            R.id.kbiTask, R.id.kbtKcidTask, R.id.kbtNameTask, R.id.kbtAccountTask, R.id.kbtTickTask,
            R.id.kbtStateTask, R.id.kbtQtyTask,
            R.id.kbtRunTask,
    };
    public void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, item_inc_fans, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
                TaskEach taskEach = (TaskEach)getListView(tab, position);
                String text;

                if (taskEach != null && taskEach.mBDbsAccount != null){
                    BDbsAccount account = taskEach.mBDbsAccount;
                    MAPP.showUserHead(account.HeadFile, account, holder.mView[0]);
//                    第一行
                    if (account.WorksType < 32) {
                        MSKIN.setText(String.format("%s", account.UserIdS), holder.mView[1]);
                        MAPP.showUserName(account.UserName, account.WorksType, account, holder.mView[2]);
                    }else {
                        MAPP.showUserName(account.UserName, account.WorksType, account, holder.mView[1]);
                        MSKIN.setText(" ", holder.mView[2]);
                    }
                    if ("ok".equals(account.Status)){
                        MSKIN.setText("写时" + MAPP.formatSecond(taskEach.gWriteTime), holder.mView[3]);
                    }else {
                        MSKIN.setText(account.Status, holder.mView[3]);
                    }
                    long tick = System.currentTimeMillis() - taskEach.StateTick;
                    if (taskEach.StateTick != 0) {
                        text = String.format("%s%s/%s", taskEach.RunState, (tick / 1000) + 1, taskEach.StepTime / 1000);
                    } else {
                        text = String.format("%s0/%s", taskEach.RunState, taskEach.StepTime / 1000);
                    }
                    MSKIN.setText(text, holder.mView[4]);
//                    第二行
//                    MLOGE("setTextA "+text);
                    int remainder = (int)((tick/1000) % 5);
                    if (taskEach.mBUploadPlan != null && remainder < 2) {        // 有上传计划需要显示
                        text = taskEach.mBDbsAccount.Message;
                    }else {
                        text = String.format("%s榜%s/%s/%s", taskEach.RankName, taskEach.mWorksQueue.size(), taskEach.mBlackList!=null?taskEach.mBlackList.size():0, taskEach.LastState);
                    }
                    MSKIN.setText(text, holder.mView[5]);
                    MSKIN.setText(String.format("成功%s/总%s", taskEach.SuccessQty, account.SuccessQty), holder.mView[6]);

//                    第三行
                    MSKIN.setText(taskEach.Message, holder.mView[7]);
                }else {
                    MSKIN.setBitmap(tabAppImage[tab], holder.mView[0]);
                    MSKIN.setText("点击增加任务账号", holder.mView[1]);
                    MSKIN.setText(" ", holder.mView[2]);
                    MSKIN.setText(String.format("%s个", getSize(tab)-1), holder.mView[3]);
                    long tick = System.currentTimeMillis();
                    MSKIN.setText(String.format("占用:%s%s", WorksQueue.NowName, MAPP.formatSecond(tick - WorksQueue.NowTick)), holder.mView[4]);
                    text = String.format("%s榜%s/%s/%s", WorksQueue.RankName[tab], WorksQueue.mWorksQueue[tab].size(), WorksQueue.mUserQueue[tab].size(), WorksQueue.mRankQueue[tab].size());
                    MSKIN.setText(text, holder.mView[5]);
                    // 显示阵列的占用
                    MSKIN.setText(String.format("成功%s/总%s", gSuccessQty, gSuccessAll), holder.mView[6]);
                    if (MAPP.mWorksType[tab] < 32) {
                        text = String.format("写占用:%s %s", MAPP.mBLock32.Text, MAPP.formatSecond(tick - MAPP.mBLock32.Tick));
                    }else {
                        text = String.format("写占用:%s %s", MAPP.mBLock33.Text, MAPP.formatSecond(tick - MAPP.mBLock33.Tick));
                    }
                    MSKIN.setText(text, holder.mView[7]);
                }
                holder.mView[0].setTag(taskEach);
                holder.mView[0].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startPage(v);
                    }
                });
                holder.mItemView.setTag(taskEach);
                holder.mItemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startPage(v);
                    }
                });
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        mKcListView[tab].setStatus(false, false, "", null, null);
        mKcListView[tab].setTabNumber(tab);
        mKcListView[tab].setSpaceHeight(MRAM.g4ScreenWidth);
    }

    private void initTabList(){
        ViewPager viewPager = findViewById(R.id.vpMain);
        TabLayout tabLayout = findViewById(R.id.tlMain);;
        mKcListView = new KcListView[MAPP.mWorksType.length];
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return MAPP.mWorksType.length;
            }
            @Override
            public CharSequence getPageTitle(int position) {
                int worksType = MAPP.mWorksType[position];
                return MAPP.mWorksName[worksType];
            }
            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                KcListView kcListView = new KcListView(getActivity(), null);
                initListView(position, kcListView);
                container.addView(kcListView);
                setTabList(position);                               // 设置Tab的位置
//                MLOG(String.format("AddTaskPageD %s", mMyWorks.mEventHandler));
                return kcListView;
            }
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mKcListView[position]);
                mKcListView[position] = null;
            }
        };
        viewPager.setAdapter(mPagerAdapter);
        viewPager.setCurrentItem(gTabSelect);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);       // 设置TabLayout的模式   MODE_SCROLLABLE为滑动模式  MODE_FIXED为不滑动模式
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabSelected(TabLayout.Tab tab) {   // 顶部Tab选择
                byte tabSel = (byte) tab.getPosition();
                if (gTabSelect != tabSel) {                 // Tab的选择
                    gTabSelect = tabSel;
                    setTabList(tabSel);                     // 设置Tab的位置
                    MSKIN.setMemoryInt(W.IncFans_gTabSelect, tabSel, false);
                }
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
}
